package com.css.fxfzypg.modules.maps.controller;

import com.css.fxfzypg.base.response.RestResponse;
import com.css.fxfzypg.modules.maps.entity.MapQueryParams;
import com.css.fxfzypg.modules.maps.service.XqhResultsMapService;
import com.css.fxfzypg.modules.saresults.entity.DzqhXqhBasicMapEntity;
import com.css.fxfzypg.modules.saresults.vo.SaResultsHlVo;
import com.css.fxfzypg.web.PlatformSessionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author zyt
 * @create 2022-12-23 11:30
 * 小区划成果Shp文件上传
 */
@RestController
@RequestMapping("/xqhResultsMap")
@Slf4j
public class XqhResultsMapController {

    @Resource
    private XqhResultsMapService xqhResultsMapService;//地图使用

    //获取配置文件的上传文件路径
    @Value("${file.upload.path}")
    private String uploadPath;

    /**
     * 批量上传文件
     *
     * @param files
     * @return
     */
    @PostMapping("/uploadShpFile")
    public RestResponse uploadShpFile(@RequestParam("files") MultipartFile[] files, MapQueryParams queryParams) {
        System.out.println(new Date()+"-----------1.开始上传文件");
        //数据校验
        if (files == null && files.length <= 0) {
            return RestResponse.fail("上传失败，请选择文件");
        }
        //项目id
        String projectId = queryParams.getProjectId();
        //项目名称
        String projectName = queryParams.getProjectName();

        // 返回的消息
        StringBuilder returnMsg = new StringBuilder();

        String jxfilename = "";//shp文件名
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        String formatDate = df.format(new Date());

        //循环处理每一个文件
        for (MultipartFile file : files) {
            //获取上传原文件名称
            String oldFileName = file.getOriginalFilename();
            String newFileName = "";
            // 上传后文件名
            String fName = oldFileName.substring(0, oldFileName.indexOf(".")), postfix = oldFileName.substring(oldFileName.indexOf("."));
            String prefix = "小区划成果_";
            String district = projectName;
            newFileName = prefix + "_" + district + "_" + fName + "_" + formatDate + postfix;
            if (newFileName.contains(".shp") && newFileName.endsWith(".shp")) {
                jxfilename = newFileName;
            }
            File folder = new File(uploadPath);
            File savefile = new File(uploadPath + newFileName);
            if (!savefile.getParentFile().exists()) {
                savefile.getParentFile().mkdirs();
            }
            try {
                //file.transferTo(savefile);
                //File _file = new File(uploadPath + newFileName);
                //FileUtils.copyInputStreamToFile(file.getInputStream(), _file);
                //上传文件
                file.transferTo(new File(folder, newFileName));
                returnMsg.append(oldFileName);
                returnMsg.append(",");
            } catch (IOException e) {
                e.printStackTrace();
                return RestResponse.fail(oldFileName + "上传失败");
            }
            returnMsg.append(oldFileName);
            returnMsg.append(",");
        }
        System.out.println(new Date()+"-----------2.上传文件成功--"+jxfilename);
        String resultMsg = returnMsg.substring(0, returnMsg.length() - 1);
        String resMsg = "";
        String userID = PlatformSessionContext.getUserID();//登录用户ID
        System.out.println(new Date()+"-----------3.开始importShapeFile");
        resMsg = xqhResultsMapService.checkSHPFiles(uploadPath + jxfilename, projectId);
        System.out.println(new Date()+"-----------4.结束importShapeFile");
        if(resMsg.indexOf("导入成功") != -1){//上传成功
            System.out.println(new Date()+"-----------5.上传成功." + resMsg);
        }else{
            System.out.println(new Date()+"-----------5.上传失败." + resMsg);
        }
        if (resMsg.indexOf("checkNotCGCS2000") != -1) return RestResponse.succeed("请上传正确的CGCS2000坐标系数据及.prj文件.");
        if (resMsg.indexOf("messyCode") != -1) return RestResponse.succeed("导入.dbf文件的属性的第【" + resMsg.split("#")[1] + "】条数据信息有乱码.");
        if (resMsg.indexOf("fieldNullValue") != -1) return RestResponse.succeed("上传文件中字段值存在空值, 请对照字段说明检查数据的正确性.");
        //if (resMsg.indexOf("PointIsNotInDistrict") != -1) return RestResponse.succeed("存在没有位于 【" + province + city + area + "】 行政边界的数据, 请检查数据的正确性.");
        //if (resMsg.indexOf("GeometryIsNotEqualsCoordinate") != -1) return RestResponse.succeed("填报经纬度属性值与Geometry不一致, 请检查数据正确性.");
        if(resMsg.indexOf("fieldNumError")!=-1) return RestResponse.succeed("上传文件中字段数量不符合要求, 请对照字段说明检查数据的正确性.");
        //if(resMsg.indexOf("PointOverlapError")!=-1) return RestResponse.succeed("上传文件中数据存在空间位置重叠, 请检查数据的正确性.");

        return RestResponse.succeed(resultMsg + "上传成功.<br/>" + resMsg);
    }

    /**
     * 小区划成果目录根据经纬度获取geomText值
     * @param
     * @return
     */
    @PostMapping("getGeomTextByLonLatString")
    public RestResponse getGeomTextByLonLatString(@RequestBody DzqhXqhBasicMapEntity mapEntity) {
        String[] longitude = mapEntity.getLongitude().split(",");
        String[] latitude = mapEntity.getLatitude().split(",");
        return RestResponse.succeed(xqhResultsMapService.getGeomTextByLonLatString(longitude, latitude));
    }

    /**
     * 小区划成果目录项目信息地图圈选查询
     * @param
     * @return
     */
    @GetMapping("queryXqhResultsProjectByGeomText")
    public RestResponse queryXqhResultsProjectByGeomText(DzqhXqhBasicMapEntity mapEntity, HttpServletRequest request) {
        String geomText = String.valueOf(request.getParameter("geomText"));
        return RestResponse.succeed(xqhResultsMapService.queryXqhResultsProjectByGeomText(mapEntity, geomText));
    }

    /**
     * 小区划成果目录孔位信息地图圈选查询
     * @param
     * @return
     */
    @GetMapping("queryXqhResultsHlByGeomText")
    public RestResponse queryXqhResultsHlByGeomText(SaResultsHlVo saResultsHlVo, HttpServletRequest request) {
        String geomText = String.valueOf(request.getParameter("geomText"));
        return RestResponse.succeed(xqhResultsMapService.queryXqhResultsHlByGeomText(saResultsHlVo, geomText));
    }
}
